package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.refund.pojo.dto.RefundUpdateBatchDTO;
import com.xbongbong.pro.refund.pojo.dto.RefundUpdateDTO;
import com.xbongbong.pro.refund.pojo.vo.RefundUpdateBatchVO;
import com.xbongbong.pro.returnedpurchase.pojo.dto.ReturnedPurchaseUpdateBatchDTO;
import com.xbongbong.pro.returnedpurchase.pojo.dto.ReturnedPurchaseUpdateDTO;
import com.xbongbong.pro.returnedpurchase.pojo.vo.ReturnedPurchaseUpdateBatchVO;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ext.PayPlanSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.RefundEntityExt;
import com.xbongbong.saas.domain.entity.ext.ReturnedPurchaseEntityExt;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PaymentSheetModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.model.ReturnedPurchaseModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;

/**
 * @author: 汪腾伟
 * @date: Created in 2021/9/18 16:45
 * @description： 退货退款帮助类
 */
@Component
public class SaasRefundHelper {

    private static final Logger LOG = LoggerFactory.getLogger(SaasRefundHelper.class);


    @Resource
    private PaymentSheetModel paymentSheetModel;
    @Resource
    private RefundModel refundModel;
    @Resource
    private ReturnedPurchaseModel returnedPurchaseModel;
    @Resource
    private PayPlanSheetModel payPlanSheetModel;

    /**
     * 更新退货退款中的回款单ID
     * @param refundId 退货退款ID
     * @param paasFormDataEntity 回款单实体
     * @param corpid 入参
     * @throws XbbException error
     * @author zhouwq
     * @date 2019/12/19 11:17
     */
    public void updateRefundPaymentSheetId(Long refundId, PaasFormDataEntity paasFormDataEntity, String corpid) throws XbbException {
        RefundUpdateBatchDTO refundUpdateBatchDTO = new RefundUpdateBatchDTO();
        refundUpdateBatchDTO.setCorpid(corpid);
        List<RefundUpdateDTO> refundUpdateList = new ArrayList<>();
        RefundUpdateDTO refundUpdateDTO = new RefundUpdateDTO();
        refundUpdateDTO.setId(refundId);
        JSONObject newData = new JSONObject();
        RefundEntityExt refundEntityExt = refundModel.getByKey(refundId, corpid);
        JSONObject oldData = refundEntityExt.getData();
        JSONArray paymentSheetIds = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData, RefundEnum.PAYMENT_SHEETS.getAttr(), new JSONArray());
        paymentSheetIds.add(paasFormDataEntity.getId());
        newData.put(RefundEnum.PAYMENT_SHEETS.getAttr(), paymentSheetIds);
        JSONArray paymentSheetNames = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData, RefundEnum.PAYMENT_SHEETS_LINKED_TEXT.getAttr(), new JSONArray());
        paymentSheetNames.add(paasFormDataEntity.getSerialNo());
        newData.put(RefundEnum.PAYMENT_SHEETS_LINKED_TEXT.getAttr(), paymentSheetNames);
        //查询回款单实体
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("idIn", paymentSheetIds);
        param.put(StringConstant.CORPID, corpid);
        List<PaymentSheetEntityExt> paymentSheets = paymentSheetModel.findEntitys(param);
        double paymentSheetAmount = 0D;
        for (PaymentSheetEntityExt paymentSheet : paymentSheets) {
            JSONObject paymentSheetData = paymentSheet.getData();
            Double oldPaymentSheetAmount = getDoubleOrDefaultFromFormData(paymentSheetData, PaymentSheetEnum.AMOUNT.getAttr(), 0D);
            paymentSheetAmount = Arith.add(oldPaymentSheetAmount, paymentSheetAmount);
        }
        newData.put(RefundEnum.REFUND_AMOUNT.getAttr(), Math.abs(paymentSheetAmount));
        refundUpdateDTO.setData(newData);
        refundUpdateList.add(refundUpdateDTO);
        refundUpdateBatchDTO.setRefundUpdateList(refundUpdateList);
        try{
            updateBatch(refundUpdateBatchDTO);
        } catch (XbbException e) {
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200019);
        }
    }

    public RefundUpdateBatchVO updateBatch(RefundUpdateBatchDTO refundUpdateBatchDTO) throws XbbException {
        RefundUpdateBatchVO refundUpdateBatchVO = new RefundUpdateBatchVO();
        try {
            String corpid = refundUpdateBatchDTO.getCorpid();
            List<UpdateDataEntity> updateList = new ArrayList<>();
            List<RefundUpdateDTO> contractUpdateList = refundUpdateBatchDTO.getRefundUpdateList();
            if (Objects.nonNull(contractUpdateList) && !contractUpdateList.isEmpty()) {
                contractUpdateList.forEach((item)->{
                    updateList.add(ExplainUtil.getUpdateData(item.getId(), item.getData(), corpid));
                });
            }
            if (!updateList.isEmpty()) {
                refundModel.updateBatch(updateList, corpid);
            }
        } catch (Exception e) {
            LOG.error("refundServiceImpl.updateBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return refundUpdateBatchVO;
    }

    public void updateReturnedPurchasePaySheetId(Long returnedPurchaseId, PaasFormDataEntity paasFormDataEntity, String corpid) throws XbbException {
        ReturnedPurchaseUpdateBatchDTO returnedPurchaseUpdateBatchDTO = new ReturnedPurchaseUpdateBatchDTO();
        returnedPurchaseUpdateBatchDTO.setCorpid(corpid);
        List<ReturnedPurchaseUpdateDTO> returnedPurchaseUpdateList = new ArrayList<>();
        ReturnedPurchaseUpdateDTO returnedPurchaseUpdateDTO = new ReturnedPurchaseUpdateDTO();
        returnedPurchaseUpdateDTO.setId(returnedPurchaseId);
        JSONObject newData = new JSONObject();
        ReturnedPurchaseEntityExt returnedPurchaseEntityExt = returnedPurchaseModel.getByKey(returnedPurchaseId, corpid);
        JSONObject oldData = returnedPurchaseEntityExt.getData();
        JSONArray paySheetIds = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData, ReturnedPurchaseEnum.PAY_SHEETS.getAttr(), new JSONArray());
        paySheetIds.add(paasFormDataEntity.getId());
        newData.put(ReturnedPurchaseEnum.PAY_SHEETS.getAttr(), paySheetIds);
        JSONArray paymentSheetNames = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData, ReturnedPurchaseEnum.PAY_SHEETS_LINKED_TEXT.getAttr(), new JSONArray());
        paymentSheetNames.add(paasFormDataEntity.getSerialNo());
        newData.put(ReturnedPurchaseEnum.PAY_SHEETS_LINKED_TEXT.getAttr(), paymentSheetNames);
        //查询回款单实体
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("idIn", paySheetIds);
        param.put(StringConstant.CORPID, corpid);
        List<PayPlanSheetEntityExt> paySheets = payPlanSheetModel.findEntitys(param);
        double paySheetAmount = 0D;
        for (PayPlanSheetEntityExt paySheet : paySheets) {
            JSONObject paySheetData = paySheet.getData();
            Double oldPaymentSheetAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(paySheetData, PaySheetEnum.AMOUNT.getAttr(), 0D);
            paySheetAmount = Arith.add(oldPaymentSheetAmount, paySheetAmount);
        }
        newData.put(ReturnedPurchaseEnum.RETURNED_PURCHASE_AMOUNT.getAttr(), Math.abs(paySheetAmount));
        returnedPurchaseUpdateDTO.setData(newData);
        returnedPurchaseUpdateList.add(returnedPurchaseUpdateDTO);
        returnedPurchaseUpdateBatchDTO.setReturnedPurchaseList(returnedPurchaseUpdateList);
        try{
            updateBatch(returnedPurchaseUpdateBatchDTO);
        } catch (XbbException e) {
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200019);
        }
    }

    public ReturnedPurchaseUpdateBatchVO updateBatch(ReturnedPurchaseUpdateBatchDTO returnedPurchaseUpdateBatchDTO) throws XbbException {
        ReturnedPurchaseUpdateBatchVO returnedPurchaseUpdateBatchVO = new ReturnedPurchaseUpdateBatchVO();
        try {
            String corpid = returnedPurchaseUpdateBatchDTO.getCorpid();
            List<UpdateDataEntity> updateList = new ArrayList<>();
            List<ReturnedPurchaseUpdateDTO> returnedPurchaseList = returnedPurchaseUpdateBatchDTO.getReturnedPurchaseList();
            if (Objects.nonNull(returnedPurchaseList) && !returnedPurchaseList.isEmpty()) {
                returnedPurchaseList.forEach((item)->{
                    updateList.add(ExplainUtil.getUpdateData(item.getId(), item.getData(), corpid));
                });
            }
            if (!updateList.isEmpty()) {
                returnedPurchaseModel.updateBatch(updateList, corpid);
            }

        } catch (Exception e) {
            LOG.error("returnedPurchaseServiceImpl.updateBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return returnedPurchaseUpdateBatchVO;
    }
}
